package com.googlecode.recycled.xml;

import org.apache.commons.lang.UnhandledException;
import org.w3c.dom.Node;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

/**
 * @author Henryk Konsek
 */
public class XmlPrinter {

    boolean omitXmlDeclaration = true;

    public XmlPrinter omitXmlDeclaration(boolean omitXmlDeclaration) {
        this.omitXmlDeclaration = omitXmlDeclaration;
        return this;
    }

    public String toString(Node node) {
        StringWriter sw = new StringWriter();
        try {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            if (omitXmlDeclaration) {
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            }
            transformer.transform(new DOMSource(node), new StreamResult(sw));
        } catch (TransformerException e) {
            throw new UnhandledException(e);
        }
        return sw.toString();
    }

}
